from django.db import models
from django.conf import settings
from utils.sharded_models import ShardedOrder
from utils.snowflake import generate_id


class Department(models.Model):
    """科室模型（对应图一）"""
    # 自关联实现科室层级结构
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='children',
        verbose_name="上级科室"
    )
    name = models.CharField(max_length=50, verbose_name="科室名称")
    campus = models.CharField(max_length=20, default="东院", verbose_name="所属院区")
    address = models.CharField(max_length=100, verbose_name="科室地址")
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    class Meta:
        verbose_name = "Department"
        verbose_name_plural = "科室"
        ordering = ['-create_time']

    def __str__(self):
        return self.full_path

    @property
    def full_path(self):
        """获取科室完整路径（如：内科/心脏内科）"""
        path = []
        node = self
        while node:
            path.append(node.name)
            node = node.parent
        return '/'.join(reversed(path))


class Doctor(models.Model):
    """医生模型（对应图二）"""
    name = models.CharField(max_length=20, verbose_name="医生姓名")
    #默认30元
    price = models.DecimalField(max_digits=10, decimal_places=2, default=30.00, verbose_name="医生费用")
    avatar = models.ImageField(upload_to='doctors/', blank=True, verbose_name="医生头像")
    department = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        related_name='doctors',
        verbose_name="所属科室"
    )
    title = models.CharField(max_length=20, verbose_name="职称")
    tags = models.CharField(max_length=100, help_text="用逗号分隔", verbose_name="医疗标签")
    introduction = models.TextField(verbose_name="医生简介")
    campus = models.CharField(max_length=20, default="东院", verbose_name="执业院区")
    class Meta:
        verbose_name = "doctor"
        verbose_name_plural = "医生"

    def __str__(self):
        return f"{self.name} ({self.title})"

    @property
    def full_department(self):
        """获取带父科室的完整科室名称（如：内科-肾内科）"""
        return f"{self.department.parent.name}-{self.department.name}" if self.department.parent else self.department.name

#用户表
class User(models.Model):
    #可以为空
    username = models.CharField(max_length=20, verbose_name="用户名",  null=True)
    password = models.CharField(max_length=20, verbose_name="密码",  null=True)
    email = models.CharField(max_length=20, verbose_name="邮箱",  null=True)
    phone = models.CharField(max_length=20, verbose_name="手机号")
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    class Meta:
        verbose_name = "User"
        verbose_name_plural = "用户"
        ordering = ['-create_time']

class Hospital(models.Model):
    """医院信息模型"""
    name = models.CharField(max_length=100, verbose_name="医院名称")
    address = models.CharField(max_length=200, verbose_name="医院地址")
    campus = models.CharField(max_length=50, verbose_name="院区")
    
    class Meta:
        verbose_name = "医院"
        verbose_name_plural = "医院"

    def __str__(self):
        return f"{self.name}-{self.campus}"

class Schedule(models.Model):
    """医生排班表"""
    doctor = models.ForeignKey(
        Doctor,
        on_delete=models.CASCADE,
        related_name='doctor_schedules',
        verbose_name="医生"
    )
    date = models.DateField(verbose_name="排班日期")
    total_numbers = models.IntegerField(default=30, verbose_name="总号源数")
    booked_numbers = models.IntegerField(default=0, verbose_name="已预约数")
    status = models.CharField(
        max_length=20,
        choices=[('available', '可约'), ('full', '约满'), ('closed', '停诊')],
        default='available',
        verbose_name="状态"
    )
    
    class Meta:
        verbose_name = "排班表"
        verbose_name_plural = "排班表"
        unique_together = ['doctor', 'date']

    @property
    def available_numbers(self):
        return max(0, self.total_numbers - self.booked_numbers)

class TimeSlot(models.Model):
    """预约时间段"""
    schedule = models.ForeignKey(
        Schedule,
        on_delete=models.CASCADE,
        related_name='time_slots',
        verbose_name="排班"
    )
    start_time = models.TimeField(verbose_name="开始时间")
    end_time = models.TimeField(verbose_name="结束时间")
    total_numbers = models.IntegerField(default=10, verbose_name="时段号源数")
    booked_numbers = models.IntegerField(default=0, verbose_name="已预约数")
    
    class Meta:
        verbose_name = "预约时间段"
        verbose_name_plural = "预约时间段"
        ordering = ['start_time']
        unique_together = ['schedule', 'start_time']

    @property
    def available_numbers(self):
        return max(0, self.total_numbers - self.booked_numbers)

    def __str__(self):
        return f"{self.start_time.strftime('%H:%M')}-{self.end_time.strftime('%H:%M')}"

class MedicalArticle(models.Model):
    """医疗文章模型"""
    title = models.CharField(max_length=200, verbose_name="文章标题")
    content = models.TextField(verbose_name="文章内容")
    author = models.CharField(max_length=50, verbose_name="作者")
    department = models.ForeignKey(
        Department,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="articles",
        verbose_name="相关科室"
    )
    tags = models.CharField(max_length=200, verbose_name="标签", help_text="用逗号分隔")
    image = models.ImageField(upload_to='articles/', blank=True, null=True, verbose_name="配图")
    view_count = models.IntegerField(default=0, verbose_name="浏览次数")
    like_count = models.IntegerField(default=0, verbose_name="点赞数")
    status = models.CharField(
        max_length=20,
        choices=[
            ('draft', '草稿'),
            ('published', '已发布'),
            ('archived', '已归档')
        ],
        default='published',
        verbose_name="状态"
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "医疗文章"
        verbose_name_plural = "医疗文章"
        ordering = ['-created_at']
        
    def __str__(self):
        return self.title
        
    @property
    def tag_list(self):
        """返回标签列表"""
        return self.tags.split(',') if self.tags else []
        
    def save(self, *args, **kwargs):
        """重写保存方法，自动同步到ES"""
        # 先保存到数据库
        super().save(*args, **kwargs)
        # 然后同步到ES
        self.sync_to_elasticsearch()
        
    def delete(self, *args, **kwargs):
        """重写删除方法，自动从ES中删除"""
        # 在删除前从ES中删除
        self.sync_to_elasticsearch(delete=True)
        # 然后从数据库删除
        super().delete(*args, **kwargs)
        
    def sync_to_elasticsearch(self, delete=False):
        """同步当前文章到Elasticsearch"""
        try:
            # 导入ES同步管理器
            from .es_utils.es_sync import ElasticsearchSyncManager
            # 同步当前文章
            ElasticsearchSyncManager.sync_article_to_es(self, delete=delete)
        except Exception as e:
            # 记录错误但不中断操作
            import logging
            logger = logging.getLogger('elasticsearch')
            logger.error(f"同步文章到ES失败: id={self.id}, error={str(e)}")
            # 在开发环境打印错误
            if settings.DEBUG:
                print(f"ES同步错误: {str(e)}")
                import traceback
                print(traceback.format_exc())